package com.example.wanandroid.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.example.wanandroid.R;
import com.example.wanandroid.activity.DataContentActivity;
import com.example.wanandroid.entity.ArticleBean;
import com.example.wanandroid.utils.GlideUtils;
import com.example.wanandroid.view.ItemDivider;
import com.kymjs.rxvolley.RxVolley;
import com.kymjs.rxvolley.client.HttpCallback;
import com.kymjs.rxvolley.toolbox.Loger;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.BallPulseFooter;
import com.scwang.smartrefresh.layout.header.BezierRadarHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class SystemDataFragment extends Fragment {

    private int id;
    private int curPage = 0;
    private int currentPage = 0;
    private List<String> list = new ArrayList<>();
    private List<String> listUrl = new ArrayList<>();
    private List<String> listTitle = new ArrayList<>();
    private List<ArticleBean> mList = new ArrayList<>();
    private BaseQuickAdapter<ArticleBean, BaseViewHolder> mAdapter;
    private RefreshLayout refreshLayout;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_system_data, null);

        Bundle bundle = getArguments();
        String mId = bundle.getString("mId");
        id = Integer.parseInt(mId);
        initView(view);
        initData(currentPage);

        return view;
    }

    private void initView(View view) {
        refreshLayout = view.findViewById(R.id.refreshLayout);
        //设置 Header 为 贝塞尔雷达 样式
        refreshLayout.setRefreshHeader(new BezierRadarHeader(getActivity()).setEnableHorizontalDrag(true));
        //设置 Footer 为 球脉冲 样式
        refreshLayout.setRefreshFooter(new BallPulseFooter(getActivity()).setSpinnerStyle(SpinnerStyle.Scale));
        RecyclerView recyclerView = view.findViewById(R.id.mRecyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.addItemDecoration(new ItemDivider().setDividerWith(10).setDividerColor(getActivity().getResources().getColor(R.color.view_gray)));
        mAdapter = new BaseQuickAdapter<ArticleBean, BaseViewHolder>(R.layout.article_item, mList) {
            @Override
            protected void convert(BaseViewHolder helper, ArticleBean item) {
                helper.setText(R.id.mAuthor, item.getAuthor());
                helper.setText(R.id.mTitle, item.getTitle());
                helper.setText(R.id.mChapterName, item.getChapterName());
                helper.setText(R.id.mSuperChapterName, item.getSuperChapterName());
                helper.setText(R.id.mNiceDate, item.getNiceDate());
                if (item.getEnvelopePic().equals("")) {
                    helper.getView(R.id.mImageView).setVisibility(View.GONE);
                } else {
                    helper.getView(R.id.mImageView).setVisibility(View.VISIBLE);
                    GlideUtils.loadImageview(getContext(), item.getEnvelopePic(), (ImageView) helper.getView(R.id.mImageView));
                }
            }
        };
        recyclerView.setAdapter(mAdapter);

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent = new Intent(getContext(), DataContentActivity.class);
                intent.putExtra("url", mList.get(position).getLink());
                intent.putExtra("title", mList.get(position).getTitle());
                startActivity(intent);
            }
        });

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {

                refreshlayout.finishRefresh(200/*,false*/);//传入false表示刷新失败
                currentPage = 0;
                initData(currentPage);
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                refreshlayout.finishLoadMore(200/*,false*/);//传入false表示加载失败
                initData(currentPage);
            }
        });
        refreshLayout.setEnableLoadMore(true);
        //refreshLayout.autoRefresh();
    }

    private void initData(final int page) {
        list.clear();
        listUrl.clear();
        listTitle.clear();
        //get请求简洁版实现
        RxVolley.get("http://www.wanandroid.com/article/list/" + page + "/json?cid=" + id, new HttpCallback() {
            @Override
            public void onSuccess(String data) {
                Loger.debug("请求到的数据:" + data);
                if (!TextUtils.isEmpty(data)) {
                    getTabData(data, page);
                }
            }
        });
    }

    private void getTabData(String data, int page) {
        try {
            JSONObject jsonObject = new JSONObject(data);
            JSONObject jsonObjectData = jsonObject.getJSONObject("data");
            curPage = jsonObjectData.getInt("curPage");
            JSONArray jsonArray = jsonObjectData.getJSONArray("datas");
            if (page > curPage) {
                Toast.makeText(getContext(), "数据加载完毕", Toast.LENGTH_SHORT).show();
            } else {
                if (currentPage == 0) {
                    mList.clear();
                }
                for (int i = 0; i < jsonArray.length(); i++) {
                    ArticleBean articleBean = new ArticleBean();
                    JSONObject jsonDatas = (JSONObject) jsonArray.get(i);
                    articleBean.setAuthor(jsonDatas.getString("author"));
                    Log.d("rcl", "==getTabData: ==" + jsonDatas.getString("author"));
                    articleBean.setChapterName(jsonDatas.getString("chapterName"));
                    articleBean.setEnvelopePic("");
                    articleBean.setTitle(jsonDatas.getString("title"));
                    articleBean.setSuperChapterName(jsonDatas.getString("superChapterName"));
                    articleBean.setLink(jsonDatas.getString("link"));
                    articleBean.setNiceDate(jsonDatas.getString("niceDate"));
                    mList.add(articleBean);
                    mAdapter.notifyDataSetChanged();
                }
                currentPage++;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
